//
//  Test2dPhysics.cpp
//  NanoOSX
//
//  Created by Jeppe Nielsen on 12/28/13.
//  Copyright (c) 2013 Jeppe Nielsen. All rights reserved.
//

#include "Engine.hpp"
#include "OpenGL.hpp"
#include "GameWorld.hpp"
#include "RenderSystem.hpp"
#include "Light.hpp"
#include "FirstPersonMoverSystem.hpp"
#include "PhysicsSystem2d.hpp"

using namespace Nano;

class Test2dPhysics : public GameState {
    
    GameWorld world;
    RenderSystem* renderer;
    GameObject* cube;
    
    
    void Initialized() {
        renderer = world.CreateSystem<RenderSystem>();
        world.CreateSystem<FirstPersonMoverSystem>()->Input = &Input;
        world.CreateSystem<PhysicsSystem2d>();
        
        GameObject* camera = world.CreateObject();
        camera->AddComponent<Transform>()->Position = Vector3(0,0,4);
        camera->AddComponent<Camera>()->Viewport = Viewport();
        camera->AddComponent<FirstPersonMover>();
        
        GameObject* grass = world.CreateObject();
        grass->AddComponent<TextureComponent>()->Texture().LoadFromPng("grass.png");
        
        {
            GameObject* floor = world.CreateObject();
            floor->AddComponent<Transform>();
            floor->AddComponent<Mesh>()->AddCube(0, {25,0.2f,0.2f});
            floor->AddComponent<TextureComponent>(grass);
            floor->AddComponent<Material>();
            b2PolygonDef& polygon = floor->AddComponent<RigidBody2d>()->CreatePolygon();
            polygon.SetAsBox(25.0f, 0.2f);
        }
        
        for (int i=0; i<10; i++)
        {
            cube = world.CreateObject();
            cube->AddComponent<Transform>()->Position = {i&1 ? -1 : 0,5+i * 2,0};
            cube->AddComponent<Mesh>()->AddCube(0, {1,1,0.2f});
            cube->AddComponent<TextureComponent>(grass);
            cube->AddComponent<Material>();
            b2PolygonDef& polygon = cube->AddComponent<RigidBody2d>()->CreatePolygon(1.0f);
            polygon.SetAsBox(1, 1);
        }
        
        for (int i=0; i<10; i++)
        {
            cube = world.CreateObject();
            cube->AddComponent<Transform>()->Position = {i&1 ? -3 : -2,2+i * 2,0};
            cube->AddComponent<Mesh>()->AddGeoSphere(0, 1, 10);
            cube->AddComponent<TextureComponent>(grass);
            cube->AddComponent<Material>();
            b2CircleDef& circle = cube->AddComponent<RigidBody2d>()->CreateCircle(1.0f);
            circle.radius = 1;
        }

        
    }
    
    void Update(float dt) {
        world.Update(dt);
    }
    
    void Render() {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glEnable(GL_CULL_FACE);
        glEnable(GL_DEPTH);
        renderer->Render();
    }
};

/*
int main() {
    Engine e;
    e.Start<Test2dPhysics>();
    return 0;
}
 */
